<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态
check_login();

$error = '';
$success = '';
$user = null;

// 获取要编辑的用户信息
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id <= 0) {
    header("Location: users.php");
    exit();
}

try {
    $db = db_connect();
    
    // 获取用户信息
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        header("Location: users.php");
        exit();
    }
    
    // 处理表单提交
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $name = safe_input($_POST['name']);
        $gender = safe_input($_POST['gender']);
        $age = intval($_POST['age']);
        $phone = safe_input($_POST['phone']);
        $email = safe_input($_POST['email']);
        $password = $_POST['password']; // 可选
        
        // 验证表单数据
        if (empty($name) || empty($phone) || empty($email)) {
            $error = '姓名、手机号和邮箱不能为空';
        } elseif (!empty($password) && strlen($password) < 6) {
            $error = '密码长度不能少于6位';
        } elseif (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $error = '手机号格式不正确';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = '邮箱格式不正确';
        } elseif ($age < 1 || $age > 120) {
            $error = '请输入有效的年龄';
        } else {
            // 检查手机号是否已被其他用户使用
            $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE phone = ? AND id != ?");
            $stmt->execute([$phone, $id]);
            if ($stmt->fetchColumn() > 0) {
                $error = '手机号已被其他用户注册';
            } else {
                // 检查邮箱是否已被其他用户使用
                $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id != ?");
                $stmt->execute([$email, $id]);
                if ($stmt->fetchColumn() > 0) {
                    $error = '邮箱已被其他用户注册';
                } else {
                    // 处理头像上传
                    $avatar = $user['avatar'];
                    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
                        $filename = $_FILES['avatar']['name'];
                        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                        
                        if (!in_array($ext, $allowed)) {
                            $error = '只允许上传 jpg, jpeg, png, gif 格式的图片';
                        } else {
                            $upload_dir = '../api/user/uploads/avatars/';
                            if (!is_dir($upload_dir)) {
                                mkdir($upload_dir, 0777, true);
                            }
                            
                            $new_filename = uniqid() . '.' . $ext;
                            if (move_uploaded_file($_FILES['avatar']['tmp_name'], $upload_dir . $new_filename)) {
                                // 删除旧头像
                                if ($user['avatar'] && file_exists($upload_dir . basename($user['avatar']))) {
                                    unlink($upload_dir . basename($user['avatar']));
                                }
                                $avatar = 'uploads/avatars/' . $new_filename;
                            }
                        }
                    }
                    
                    if (empty($error)) {
                        // 准备更新语句
                        if (!empty($password)) {
                            $sql = "UPDATE users SET name = ?, avatar = ?, gender = ?, age = ?, 
                                   phone = ?, email = ?, password = ? WHERE id = ?";
                            $params = [
                                $name, $avatar, $gender, $age, $phone, $email,
                                password_hash($password, PASSWORD_DEFAULT), $id
                            ];
                        } else {
                            $sql = "UPDATE users SET name = ?, avatar = ?, gender = ?, age = ?, 
                                   phone = ?, email = ? WHERE id = ?";
                            $params = [$name, $avatar, $gender, $age, $phone, $email, $id];
                        }
                        
                        // 执行更新
                        $stmt = $db->prepare($sql);
                        $stmt->execute($params);
                        
                        $success = '用户信息更新成功';
                        
                        // 重新获取用户信息
                        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
                        $stmt->execute([$id]);
                        $user = $stmt->fetch(PDO::FETCH_ASSOC);
                    }
                }
            }
        }
    }
} catch(PDOException $e) {
    $error = '系统错误，请稍后再试';
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑用户 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/dashboard.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>编辑用户</h2>
                </div>
                <div class="header-right">
                    <a href="users.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> 返回列表
                    </a>
                </div>
            </header>

            <div class="content">
                <div class="form-container">
                    <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="name">姓名 <span class="required">*</span></label>
                            <input type="text" id="name" name="name" required value="<?php echo htmlspecialchars($user['name']); ?>">
                        </div>

                        <div class="form-group">
                            <label for="password">密码（不修改请留空）</label>
                            <input type="password" id="password" name="password">
                        </div>

                        <div class="form-group">
                            <label for="avatar">头像</label>
                            <?php if ($user['avatar']): ?>
                            <div class="current-avatar">
                                <img src="../api/user/<?php echo htmlspecialchars($user['avatar']); ?>" alt="当前头像" style="max-width: 100px;">
                            </div>
                            <?php endif; ?>
                            <input type="file" id="avatar" name="avatar" accept="image/*">
                        </div>

                        <div class="form-group">
                            <label for="gender">性别 <span class="required">*</span></label>
                            <select id="gender" name="gender" required>
                                <option value="1" <?php echo $user['gender'] == '1' ? 'selected' : ''; ?>>男</option>
                                <option value="2" <?php echo $user['gender'] == '2' ? 'selected' : ''; ?>>女</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="age">年龄 <span class="required">*</span></label>
                            <input type="number" id="age" name="age" required min="1" max="120" value="<?php echo $user['age']; ?>">
                        </div>

                        <div class="form-group">
                            <label for="phone">手机号 <span class="required">*</span></label>
                            <input type="text" id="phone" name="phone" required value="<?php echo htmlspecialchars($user['phone']); ?>">
                        </div>

                        <div class="form-group">
                            <label for="email">邮箱 <span class="required">*</span></label>
                            <input type="email" id="email" name="email" required value="<?php echo htmlspecialchars($user['email']); ?>">
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 